import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import subprocess

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"]
)


# def execute_command(path, commands):
#     res_data = []
#     for cmd in commands:
#         process = subprocess.Popen(cmd, shell=True, cwd=path, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
#         stdout, stderr = process.communicate()
#         if process.returncode == 0:
#             stdout = stdout.decode('utf-8')
#             res_data.append(stdout)
#         else:
#             raise Exception(stderr.decode('utf-8'))
#     return res_data


@app.get("/execCmd")
async def execCmd(path, commands: list):
    res_data = []
    for cmd in commands:
        process = subprocess.Popen(cmd, shell=True, cwd=path, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = process.communicate()
        if process.returncode == 0:
            stdout = stdout.decode('utf-8')
            res_data.append(stdout)
        else:
            raise Exception(stderr.decode('utf-8'))
    return res_data


if __name__ == '__main__':
    uvicorn.run(app="exec_cmd:app", host="127.0.0.1", port=9529)
